package com.zeyi.blog.util;

import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import com.zeyi.blog.dto.MyFile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 黎先森
 */
@Component
public class QiniuUtil {

    @Value("${qiniu.accessKey}")
    String accessKey;

    @Value("${qiniu.secretKey}")
    String secretKey;

    @Value("${qiniu.bucket}")
    String bucket;

    public String getToken() {
        Auth auth = Auth.create(accessKey, secretKey);
        return auth.uploadToken(bucket);
    }

    public boolean delFile(String key) {
        Configuration cfg = new Configuration(Region.region0());
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(bucket, key);
            return true;
        } catch (QiniuException e) {
            return false;
        }
    }

    public List<MyFile> getFileList(String prefix) {
        Configuration cfg = new Configuration(Region.region0());
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        //每次迭代的长度限制，最大1000，推荐值 1000
        int limit = 100;
        //指定目录分隔符，列出所有公共前缀（模拟列出目录效果）。缺省值为空字符串
        String delimiter = "";
        List<MyFile> fileList = new ArrayList<>();
        BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(bucket, prefix, limit, delimiter);
        while (fileListIterator.hasNext()) {
            FileInfo[] items = fileListIterator.next();
            for (FileInfo item : items) {
                MyFile file = new MyFile();
                file.setKey(item.key);
                file.setFsize(item.fsize);
                file.setMimeType(item.mimeType);
                file.setPutTime(item.putTime / 10000);
                fileList.add(file);
            }
        }
        return fileList;
    }
}
